package com.only4play.auth.security.authentication.admin.password;

import org.springframework.context.ApplicationContext;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author zlm
 * @date 2024/1/24
 */
public class AdminPasswordConfigure extends AbstractHttpConfigurer<AdminPasswordConfigure, HttpSecurity> {
  @Override
  public void init(HttpSecurity builder) throws Exception {
    super.init(builder);
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {

    ApplicationContext applicationContext = http.getSharedObject(ApplicationContext.class);
    AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
    AdminPasswordLoginProcessFilter passwordLoginProcessFilter = new AdminPasswordLoginProcessFilter(builder.getObject());
    //设置成功处理器
    AuthenticationSuccessHandler successHandler = applicationContext.getBean(AuthenticationSuccessHandler.class);
    passwordLoginProcessFilter.setAuthenticationSuccessHandler(successHandler);
    //设置失败处理器
    AuthenticationFailureHandler failureHandler = applicationContext.getBean(AuthenticationFailureHandler.class);
    passwordLoginProcessFilter.setAuthenticationFailureHandler(failureHandler);
    //配置filter后请求filter
    http.addFilterBefore(passwordLoginProcessFilter, UsernamePasswordAuthenticationFilter.class);
    super.configure(http);
  }

  public static AdminPasswordConfigure adminPasswordLogin() {
    return new AdminPasswordConfigure();
  }
}
